#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>

using namespace std;

int main(int argc, char const *argv[])
{
    vector<pair<int, int> > lines[32];
    int m, n, *orders, ms[32][32], times[32][32], lasts[32][32] = { 0 };
    int i, j, mcrt, ocrt, lcrt, last, left, result;
    cin >> m >> n;
    orders = new int[m * n];
    for (i = 0; i < m * n; i++)
    {
        cin >> orders[i];
    }
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= m; j++)
        {
            cin >> ms[i][j];
        }
    }
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= m; j++)
        {
            cin >> times[i][j];
        }
    }
    for (i = 1; i <= m; i++)
    {
        lines[i].push_back(make_pair(0, 0));
    }
    for (i = 0; i < m * n; i++)
    {
        ocrt = orders[i];
        for (j = 1; j <= m && lasts[ocrt][j]; j++);
        if (j > m) j = 1;
        lcrt = j;
        mcrt = ms[ocrt][j];
        // printf("ocrt:%d mcrt:%d\n", ocrt, mcrt);
        last = lasts[ocrt][j - 1];
        
        // cout << "\t";
        for (j = 1; j < lines[mcrt].size(); j++)
        {
            // cout << j;
            left = max(last, lines[mcrt][j - 1].second);
            // printf(" left:%d lines[mcrt][j].first:%d", left, lines[mcrt][j].first - times[ocrt][lcrt]);
            if (lines[mcrt][j].first - times[ocrt][lcrt] >= left)
            {
                lines[mcrt].insert(lines[mcrt].begin() + j, make_pair(left, left + times[ocrt][lcrt]));
                lasts[ocrt][lcrt] = left + times[ocrt][lcrt];  
                // cout << "\t?" << left << "-" << left + times[ocrt][lcrt] << "\n";
                break;            
            }
        }

        // printf("\tj:%d lines[mcrt].size():%d\n", j, lines[mcrt].size());

        if (j == lines[mcrt].size())
        {
            left = max(lines[mcrt][lines[mcrt].size() - 1].second, last);
            lines[mcrt].push_back(make_pair(left, left + times[ocrt][lcrt]));
            lasts[ocrt][lcrt] = left + times[ocrt][lcrt];
            // cout << "\t!" << left << "-" << left + times[ocrt][lcrt] << "\n";
        }

        // cout << "\t" << mcrt << "\n";
        // for (j = 0; j < lines[mcrt].size(); j++)
        // {
        //     cout << "\t" << lines[mcrt][j].first << "-" << lines[mcrt][j].second << " "; 
        // }
        // cout << "\n";

        // cout << "\t" << ocrt << "\n\t";
        // for (j = 0; j < 32; j++)
        // {
        //     cout << lasts[ocrt][j] << " ";
        // }
        // cout << "\n";
    }

    // for (size_t i = 1; i < lines[2].size(); i++)
    // {
    //     cout << lines[2][i].first << " " << lines[2][i].second << "\n";
    // }

    result = 0;
    for (i = 1; i <= m; i++)
    {
        result = max(result, lines[i].back().second);
    }

    cout << result;

    return 0;
}
